# coding:utf-8
"""
Created on 15/7/31

@author: shenyufeng
"""

import os
import time

import yaml
import redis
import jpush
import upyun

from pymongo import MongoClient
from model import swmongo

from wechatpy import WeChatClient
from wechatpy.session.redisstorage import RedisStorage

ospath = os.path.split(__file__)[0]

run_mode = os.environ.get('RUN_ENV', 'local')

cookie_secret = "__TODO:_GENERATE_YOUR_OWN_RANDOM_VALUE_HERE__"

gconf = yaml.load(open(ospath + '/gconf.yml', 'r', encoding='utf-8'))[run_mode]
srv = yaml.load(open(ospath + '/srv.yml', 'r', encoding='utf-8'))[run_mode]
wx = yaml.load(open(ospath + '/wx.yml', 'r', encoding='utf-8'))[run_mode]
swhost = yaml.load(open(ospath + '/swms.yml', 'r', encoding='utf-8'))[run_mode]
errorDesc = yaml.load(open(ospath + '/errorDesc.yml', 'r', encoding='utf-8'))

gconf['uptime'] = time.strftime("%Y%m%d%H%M%S", time.localtime(time.time()))

# _jpush = jpush.JPush('e0f058bf35532f05f939c11b', '4c3e55399501bb145741d724')
# _jpush.set_logging("DEBUG")

msgDict = {}

srv['redis']['decode_responses'] = True
pool = redis.ConnectionPool(**srv['redis'])
rdb = redis.StrictRedis(connection_pool=pool)

if run_mode == 'loc':
    mdb = MongoClient(srv['mongo']['host'], srv['mongo']['port'])
    mdb.admin.authenticate(srv['mongo']['username'], srv['mongo']['password'], mechanism='SCRAM-SHA-1')
else:
    mongo_url = 'mongodb://{username}:{password}@{host}:{port},{host2}:{port}/admin?replicaSet={replicaSet}'.format(
        **srv['mongo'])
    mdb = MongoClient(mongo_url, connect=False)

mdb = mdb[srv['mongo']['dbname']]
# mdb = swmongo.MDB(mdb, 'sl')

wxclient = WeChatClient(wx['WX_APP_ID'], wx['WX_APP_SECRET'], session=RedisStorage(rdb))

upFile = upyun.UpYun(srv['upyun']['up_file_bucket'], srv['upyun']['up_file_uname'],
                     srv['upyun']['up_file_pwd'], timeout=30, endpoint=upyun.ED_AUTO)
